import 'dart:io';

void main() {
  List<Map<String, double>> incomeList = [];
  List<Map<String, double>> expenseList = [];

  print('=== WELCOME TO BUDGET MANAGEMENT SYSTEM ===');

  while (true) {
    print('\n1. Add Income');
    print('2. Add Expense');
    print('3. View Summary');
    print('4. Exit');
    stdout.write('Enter your choice: ');
    String? choice = stdin.readLineSync();

    if (choice == null) continue;

    if (choice == '1') {
      stdout.write('Enter income description: ');
      String? desc = stdin.readLineSync();
      stdout.write('Enter income amount: ');
      String? amountStr = stdin.readLineSync();
      double? amount = double.tryParse(amountStr ?? '');

      if (desc != null && amount != null && amount >= 0) {
        incomeList.add({desc: amount});
        print('Income added successfully.');
      } else {
        print('Invalid input! Please enter a valid description and positive amount.');
      }

    } else if (choice == '2') {
      stdout.write('Enter expense description: ');
      String? desc = stdin.readLineSync();
      stdout.write('Enter expense amount: ');
      String? amountStr = stdin.readLineSync();
      double? amount = double.tryParse(amountStr ?? '');

      if (desc != null && amount != null && amount >= 0) {
        expenseList.add({desc: amount});
        print('Expense added successfully.');
      } else {
        print('Invalid input! Please enter a valid description and positive amount.');
      }

    } else if (choice == '3') {
      double totalIncome = 0;
      double totalExpenses = 0;

      for (var i in incomeList) {
        totalIncome += i.values.first;
      }

      for (var e in expenseList) {
        totalExpenses += e.values.first;
      }

      double net = totalIncome - totalExpenses;
      print('\n--- SUMMARY ---');
      print('Total Income: \$${totalIncome.toStringAsFixed(2)}');
      print('Total Expenses: \$${totalExpenses.toStringAsFixed(2)}');

      if (net >= 0) {
        print('Your net profit is \$${net.toStringAsFixed(2)}');
        double tax = net > 0 ? net * 0.15 : 0;
        if (tax > 0) {
          print('Tax to be paid (15%): \$${tax.toStringAsFixed(2)}');
        }
      } else {
        print('Your net loss is \$${net.abs().toStringAsFixed(2)}');
      }

    } else if (choice == '4') {
      print('Exiting Budget Management System... Goodbye!');
      break;
    } else {
      print('Invalid choice! Please select 1–4.');
    }
  }
}
